import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/token.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/layout',
    component: () => import('@/views/layout'),
    redirect: '/layout/home',
    children: [
      {
        path: 'home',
        component: () => import('@/views/layout/home'),
        meta: { scrollP: 0 }
      },
      { path: 'user', component: () => import('@/views/layout/user') }
    ]
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  },
  {
    path: '/search/:keyword',
    component: () => import('@/views/search/searchResult.vue')
  },
  { path: '/articledetail', component: () => import('@/views/search/articleDetail') },
  { path: '/useredit', component: () => import('@/views/layout/user/userEdit.vue') },
  { path: '/chat', component: () => import('@/views/chat') }

]

const router = new VueRouter({
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 如果去往非登录页,但无token,立即返回登录页
  // !getToken() && to.path !== '/login' ? next({ path: '/login' }) : next()
  // 另一判断
  // 如果去往登录页,但此时已有token,则呆在原地不可跳动
  to.path === '/login' && getToken() !== null ? next(false) : next()
})

export default router
